{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.roles.tpm2;
  tcti = config.security.tpm2.tctiEnvironment;
in {
  options.roles.tpm2.enable = mkOption {
    default = false;
    type = types.bool;
  };

  config = mkIf cfg.enable {
    environment = {
      sessionVariables.TSS2_FAPICONF = pkgs.runCommand "fapi-config.json" {} ''
        cp ${pkgs.tpm2-tss}/etc/tpm2-tss/fapi-config.json $out
        sed -i 's|/nix/store/[^/]*/var|/var|' $out
        sed -i 's|"tcti":.*$|"tcti": "${tcti.interface}:${tcti.deviceConf}",|' $out
      '';

      systemPackages = with pkgs; [
        tpm2-tools
      ];
    };

    security.tpm2 = {
      enable = true;
      pkcs11.enable = true;
      tctiEnvironment.enable = true;
    };
  };
}
